<?php

namespace app\admin\controller\teacher;

use app\common\controller\Backend;
use app\common\model\BehaviorCategory;
use app\common\model\Teacher;

class Ranking extends Backend
{
    /**
     * @var \app\common\model\BehaviorRecord
     */
    protected $model = null;
    protected $searchFields = 'name';
    protected $noNeedRight = ['searchList', 'cxSelect'];
    protected $schoolLimit = true;
    protected $relationSearch = true;

    protected $categoryType = [BehaviorCategory::CLASSES, BehaviorCategory::STUDENT];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('BehaviorRecord');
    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $behavior_category_id = $this->request->request('id');

            $offset = $this->request->get("offset", 0);
            $limit = $this->request->get("limit", 0);

            $count = $this->model
                ->alias('record')
                ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'record.id = detail.record_id')
                ->whereIn('detail.behavior_category_type', $this->categoryType)
                ->where(function ($query) use ($behavior_category_id) {
                    if (!$this->auth->isSuperAdmin()) {
                        $query->whereIn('record.school_id', $this->auth->getSchoolIds());
                    }
                    if ($behavior_category_id) {
                        $query->where('detail.behavior_category_id', $behavior_category_id);
                    }
                })
                ->group('record.teacher_id')
                ->count();

            $list = $this->model
                ->alias('record')
                ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'record.id = detail.record_id')
                ->whereIn('detail.behavior_category_type', $this->categoryType)
                ->where(function ($query) use ($behavior_category_id) {
                    if (!$this->auth->isSuperAdmin()) {
                        $query->whereIn('record.school_id', $this->auth->getSchoolIds());
                    }
                    if ($behavior_category_id) {
                        $query->where('detail.behavior_category_id', $behavior_category_id);
                    }
                })
                ->field('record.teacher_id,sum(detail.score) score,json_data')
                ->group('record.teacher_id')
                ->orderRaw('CONVERT(SUM(detail.score),DECIMAL(10,2)) desc')
                ->limit($offset, $limit)
                ->select();

            if ($list) {

                $list = collection($list)->toArray();

                $teacher_ids = array_column($list, 'teacher_id');
                $teachers = Teacher::alias('teacher')
                    ->join('__USER__ user', 'user.id = teacher.user_id')
                    ->whereIn('teacher.id', $teacher_ids)->column('teacher.id,teacher.name,user.mobile');

                $max_score = current($list)['score'];
                $record_count = $this->model
                    ->alias('record')
                    ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'record.id = detail.record_id')
                    ->whereIn('detail.behavior_category_type', $this->categoryType)
                    ->where(function ($query) use ($behavior_category_id) {
                        if (!$this->auth->isSuperAdmin()) {
                            $query->whereIn('record.school_id', $this->auth->getSchoolIds());
                        }
                        if ($behavior_category_id) {
                            $query->where('detail.behavior_category_id', $behavior_category_id);
                        }
                    })
                    ->group('record.teacher_id')
                    ->having('sum(detail.score) > ' . $max_score)
                    ->count();

                // 当前分数最大的人 的排名
                $sort = 1;
                if ($record_count) $sort = $record_count + 1;
                foreach ($list as $key => $value) {
                    if (isset($teachers[$value['teacher_id']])) {
                        $list[$key]['name'] = $teachers[$value['teacher_id']]['name'];
                        $list[$key]['mobile'] = $teachers[$value['teacher_id']]['mobile'];
                    }
                    //数组中第一个是当前分数最高的 排名为$sort
                    if ($key == 0) {
                        $list[$key]['sort'] = $sort;
                    } else {
                        // 继续循环
                        // 如果当前的分数与上一个的相等 那么就与上一个的排名并列
                        if ($list[$key - 1]['score'] == $value['score']) {
                            $list[$key]['sort'] = $list[$key - 1]['sort'];
                        } else {
                            // 如果不等 那就看看有没有分页情况
                            // 如果有分页 也就是说之前的所有的分数都大于当前的分数 排名累加上
                            $page_count = 0;
                            if ($offset > 0) $page_count = ($offset / $limit) * $limit - 1; // $sort已经叠加过了 所以这里 -1
                            $list[$key]['sort'] = $page_count + $sort;
                        }
                    }
                    $sort++;
                }
            }

            $result = array("total" => $count, "rows" => $list);

            return json($result);
        }

        $list = BehaviorCategory::whereIn('type', $this->categoryType)
            ->where(function ($query) {
                if (!$this->auth->isSuperAdmin()) {
                    $query->whereIn('school_id', $this->auth->getSchoolIds());
                }
            })->select();
        $this->assign('list', $list);
        $this->assignconfig('list', $list);

        return $this->view->fetch();
    }


}
